package org.ehe.business.drawing.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.ehe.business.drawing.domain.DesignDrawing;
import org.ehe.business.drawing.domain.DesignDrawingSite;
import org.ehe.business.drawing.domain.bo.DesignDrawingSiteBo;
import org.ehe.business.drawing.domain.vo.DesignDrawingSiteVo;
import org.ehe.business.drawing.mapper.DesignDrawingSiteMapper;
import org.ehe.business.drawing.service.DesignDrawingSiteService;
import org.ehe.business.project.domain.ProjectEntity;
import org.ehe.business.project.service.ProjectService;
import org.ehe.common.core.constant.RoleKeyConstants;
import org.ehe.common.core.exception.BusinessException;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.common.satoken.utils.LoginHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author :zhangnn
 * @className :DesignDrawingSiteServiceImpl
 * @description: TODO
 * @date 2025-09-25 10:04:42
 */
@Service
@RequiredArgsConstructor
public class DesignDrawingSiteServiceImpl
        extends ServiceImpl<DesignDrawingSiteMapper, DesignDrawingSite> implements DesignDrawingSiteService {

    private final ProjectService projectService;

    /**
     * 分页
     * 
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<DesignDrawingSiteVo> pageQueryList(DesignDrawingSiteBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DesignDrawingSite> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getSiteName()), DesignDrawingSite::getSiteName, bo.getSiteName());
        lqw.like(StringUtils.isNotBlank(bo.getProjectName()), DesignDrawingSite::getProjectName, bo.getProjectName());
        // 如果不是管理员角色，则只能看到自己创建的点位
        if (!(StpUtil.hasRoleOr(RoleKeyConstants.getAdminRoles().toArray(new String[0])))) {
            // 获取当前登录用户名
            String currentUsername = LoginHelper.getUsername();
            // 添加创建者过滤条件
            lqw.eq(DesignDrawingSite::getCreateBy, currentUsername);
        }

        IPage<DesignDrawingSiteVo> designDrawingSiteVoIPage = this.baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(designDrawingSiteVoIPage);
    }

    /**
     * 查询树形结构列表
     * 
     * @param bo
     * @return
     */
    @Override
    public List<DesignDrawingSiteVo> treeList(DesignDrawingSiteBo bo) {
        // 1. 构建查询条件
        LambdaQueryWrapper<DesignDrawingSite> queryWrapper = new LambdaQueryWrapper<>();

        // 必须按项目ID查询
        if (bo.getProjectId() != null) {
            queryWrapper.eq(DesignDrawingSite::getProjectId, bo.getProjectId());
        }

        // 点位名称模糊查询
        if (StrUtil.isNotBlank(bo.getSiteName())) {
            queryWrapper.like(DesignDrawingSite::getSiteName, bo.getSiteName());
        }

        // 查询所有符合条件的点位
        List<DesignDrawingSiteVo> all = baseMapper.selectVoList(queryWrapper);
        if (CollUtil.isEmpty(all)) {
            return all;
        }

        // 2. 内存拼树
        Map<Long, List<DesignDrawingSiteVo>> group = all.stream()
                .collect(Collectors.groupingBy(DesignDrawingSiteVo::getParentId));
        all.forEach(v -> v.setChildren(group.getOrDefault(v.getId(), List.of())));

        // 返回一级节点
        return group.getOrDefault(0L, List.of());
    }

    /**
     * 新增点位
     * 
     * @param bo
     * @return
     */
    @Override
    public Long addSite(DesignDrawingSiteBo bo) {
        DesignDrawingSite entity = new DesignDrawingSite();

        BeanUtils.copyProperties(bo, entity);
        entity.setCreateBy(LoginHelper.getUsername());
        entity.setTenantId(LoginHelper.getTenantId());

        ProjectEntity project = projectService.getById(bo.getProjectId());
        if (Objects.nonNull(project)) {
            entity.setProjectName(project.getProjectName());
        }

        save(entity);
        return entity.getId();
    }

    /**
     * 编辑点位
     * 
     * @param bo
     * @return
     */
    @Override
    public Boolean editSite(DesignDrawingSiteBo bo) {
        DesignDrawingSite entity = new DesignDrawingSite();
        BeanUtils.copyProperties(bo, entity);
        entity.setUpdateBy(LoginHelper.getUsername());
        return updateById(entity);
    }

    /**
     * 删除点位
     * 
     * @param id
     * @return
     */
    @Override
    public Boolean deleteSite(Long id) {
        return removeById(id);
    }

}
